package com.hawk.eye.client.logback.appender.mq;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hawk.eye.client.client.RequestParam;
import com.hawk.eye.client.logback.appender.HawkEyeBaseAppender;
import com.hawk.eye.client.toolkit.HawkEyeLogger;
import com.hawk.eye.client.toolkit.ServiceAuthHolder;
import com.hawk.eye.common.constant.AuthConstant;
import com.hawk.eye.common.model.ServiceAuthData;
import com.hawk.eye.common.utils.JsonUtil;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 自定义RocketMqAppender
 * @author: salad
 * @date: 2025/02/5
 **/
public class RocketMqProducerAppender<E> extends HawkEyeBaseAppender<E> {

    private DefaultMQProducer producer;

    private String topic = "hawk_eye_topic";

    private String tags;

    private String producerGroup = "hawk_eye_producer_group";

    private String namesrvAddr;

    @Override
    public void start() {
        if (namesrvAddr == null) {
            addError("namesrvAddr属性不能为空");
            return;
        }
        try {
            producer = new DefaultMQProducer(producerGroup);
            producer.setNamesrvAddr(namesrvAddr);
            producer.start();
        } catch (Exception e) {
            addError("初始化RocketMQ失败，请检查配置", e);
            return;
        }
        super.start();
    }


    @Override
    public void send(RequestParam requestParam){
        try {
            Message message = new Message(topic, tags, JsonUtil.toJson(requestParam).getBytes(StandardCharsets.UTF_8));
            producer.sendOneway(message);
        } catch (Exception e) {
            HawkEyeLogger.errorWithSkipSend(this.getClass(), "发送消息至RocketMQ失败: {}", e, e.getMessage());
        }
    }

    public void setTags(String tags) {
        this.tags = tags;
    }

    public void setNamesrvAddr(String namesrvAddr) {
        this.namesrvAddr = namesrvAddr;
    }

    @Override
    public void stop() {
        if (producer != null) {
            producer.shutdown();
        }
        super.stop();
    }
}
